package com.three.box.fragment

import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.graphics.drawable.GradientDrawable
import android.os.Bundle
import android.text.Editable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.widget.LinearLayoutCompat
import androidx.core.content.ContextCompat
import androidx.core.text.isDigitsOnly
import androidx.fragment.app.Fragment
import com.hjq.toast.Toaster
import com.three.box.R
import com.three.box.activity.AddProductActivity
import com.three.box.databinding.FragmentInBoxBinding
import com.three.box.dialog.GroupDialogFragment
import com.three.box.entity.Box
import com.three.box.entity.Product
import com.three.box.entity.ProductConfig
import com.three.box.network.AppRepository
import com.three.box.widget.WaitDialog


class InBoxFragmentOld : Fragment() {

    private lateinit var binding: FragmentInBoxBinding

    companion object {
        private const val TAG = "InBoxFragment"
        @JvmStatic
        fun newInstance() = InBoxFragmentOld()
    }

    private var waitDialog: WaitDialog? = null

    private val productList = mutableListOf<Product>()
    private var box: Box? = null

    private lateinit var resultLaunch: ActivityResultLauncher<Intent>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        // Inflate the layout for this fragment
        binding = FragmentInBoxBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        waitDialog = WaitDialog(requireContext())

//        initViews()

        resultLaunch = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { activityResult ->
            // 获取到Activity回传的数据
            if(activityResult.resultCode != Activity.RESULT_OK) {
                return@registerForActivityResult
            }
            val data = activityResult.data
            val resultList: ArrayList<ProductConfig>? = data?.getParcelableArrayListExtra("product_list")
            resultList?.let {  list ->
                productList.addAll(convertConfig2Product(list))
                resetValues()
            }
        }
        resetValues()
    }

    private fun convertConfig2Product(productConfigList: List<ProductConfig>): List<Product> {
        val productList = mutableListOf<Product>()
        val groupList = AppRepository.instance.productGroupList
//        productConfigList.forEach { productConfig ->
//            val model = if (productConfig.currentModel == null) productConfig.productModels[0] else productConfig.currentModel
//            val group = groupList[0]
//            productList.add(Product(
//                productId = productConfig.id,
//                productName = productConfig.name,
//                productDesc = productConfig.desc,
//                productModelId = model?.id ?: 0,
//                number = 1,
//                groupId = group.id,
//                groupName = group.name,
//                productModelName = model?.name ?: ""
//            ))
//        }

        return productList
    }

    fun addProduct() {
        if (box == null) {
            Toaster.show("请先扫码箱子二维码")
            return
        }
        resultLaunch.launch(Intent(requireActivity(), AddProductActivity::class.java))
    }

//    private fun initViews() {
//        binding.commitBtn.setOnClickListener {
//            if (box == null) {
//                Toaster.show("数据错误，请检查后重试")
//                return@setOnClickListener
//            }
//            productList.removeIf { it.number <= 0 }
//
//            box!!.products.addAll(productList)
//            LogUtils.d(TAG, JSON.toJSONString(box))
//            val boxObj = JSONObject()
//            boxObj["id"] = box!!.id
//            boxObj["boxId"] = box!!.boxId
//            val productArrayObj = JSONArray()
//            productList.forEach { product ->
//                if (product.number <= 0) {
//                    return@forEach
//                }
//                val productObj = JSONObject()
//                productObj["productId"] = product.productId
//                productObj["productModelId"] = product.productModelId
//                productObj["groupId"] = product.groupId
//                productObj["number"] = product.number
//
//                productArrayObj.add(productObj)
//            }
//            boxObj["products"] = productArrayObj
//
//            LogUtils.d(TAG, boxObj.toJSONString())
//            AppRepository.instance.saveBox(boxObj)
//
//            resetValues()
//        }
//    }

    fun onBoxLoaded(newBox: Box) {
        box = newBox
        productList.clear()
        productList.addAll(newBox.products)
        resetValues()
    }

    private fun resetValues() {
        if (box == null) {
            // show empty view
            binding.emptyLayout.visibility = View.VISIBLE
            binding.scrollView.visibility = View.GONE
            binding.descTv.text = getString(R.string.no_box_data)
            return
        }
        if (productList.isEmpty()) {
            // show empty view
            binding.emptyLayout.visibility = View.VISIBLE
            binding.scrollView.visibility = View.GONE
            binding.descTv.text = getString(R.string.no_product_data)
            return
        }
        binding.emptyLayout.visibility = View.GONE
        binding.scrollView.visibility = View.VISIBLE
        with(binding) {
//            commitBtn.isEnabled = true
            contentLayout.removeAllViews()
        }
        productList.sortBy { it.productId }

        productList.forEachIndexed { index, product ->
            binding.contentLayout.addView(buildItem(index, product))
        }
    }

    private val whiteColor = android.R.color.white
    private val blackColor = android.R.color.black

    private fun textColor(white: Boolean): Int {
        return if (white) ContextCompat.getColor(
            requireContext(),
            blackColor
        ) else ContextCompat.getColor(requireContext(), whiteColor)
    }

    private fun buildItem(index: Int, product: Product): View {
        val itemView = View.inflate(requireContext(), R.layout.item_normal, null)

        val group = AppRepository.instance.productGroupList.find { it.id == product.groupId }
        var isBgWhite = false
        if (group != null) {
            val myShapeView: View = itemView.findViewById(R.id.item_product)
            val shapeDrawable = myShapeView.background as GradientDrawable

            isBgWhite = "#ffffff".equals(group.color, ignoreCase = true)
            shapeDrawable.setColor(Color.parseColor(group.color))
        }

        val descTv = itemView.findViewById<TextView>(R.id.desc_tv)
        descTv.setTextColor(textColor(isBgWhite))
        descTv.text = getString(R.string.format_name, product.productDesc)

        val modelTv = itemView.findViewById<TextView>(R.id.model_tv)
        modelTv.setTextColor(textColor(isBgWhite))
        modelTv.text = getString(R.string.format_model, product.productModelName)

        val numberTv = itemView.findViewById<TextView>(R.id.number_tv)
        numberTv.setTextColor(textColor(isBgWhite))
        val numberEt = itemView.findViewById<EditText>(R.id.number_et)
        numberEt.setTextColor(textColor(isBgWhite))
        numberEt.text = Editable.Factory.getInstance().newEditable(product.number.toString())

        val groupTv = itemView.findViewById<TextView>(R.id.group_tv)
        groupTv.setTextColor(textColor(isBgWhite))
        groupTv.text = getString(R.string.format_group, product.groupName)
        val groupLayout = itemView.findViewById<LinearLayoutCompat>(R.id.group_layout)
        groupLayout.setOnClickListener {
            val groupDialog = GroupDialogFragment.newInstance()
            groupDialog.setCallback { group ->
                product.groupId = group.id
                product.groupName = group.name
                groupTv.text = getString(R.string.format_group, product.groupName)
                resetItem(index)
            }
            groupDialog.show(childFragmentManager, TAG)
        }

        val minusIv = itemView.findViewById<ImageView>(R.id.minus_iv)
        minusIv.setImageDrawable(minusDrawable(isBgWhite))
        val plusIv = itemView.findViewById<ImageView>(R.id.plus_iv)
        plusIv.setImageDrawable(plusDrawable(isBgWhite))
        minusIv.setOnClickListener {
            val numberText = numberEt.text.toString()
            var number = 0
            if (numberText.isNotEmpty()) {
                if (!numberText.isDigitsOnly()) {
                    Toaster.show("请输入数字")
                    return@setOnClickListener
                }
                number = numberText.toInt()
            }
            number -= 1
            if(number < 0) {
                number = 0
            }
            product.number = number
            numberEt.text = Editable.Factory.getInstance().newEditable(number.toString())
        }
        plusIv.setOnClickListener {
            val numberText = numberEt.text.toString()
            var number = 0
            if (numberText.isNotEmpty()) {
                if (!numberText.isDigitsOnly()) {
                    Toaster.show("请输入数字")
                    return@setOnClickListener
                }
                number = numberText.toInt()
            }
            number += 1
            product.number = number
            numberEt.text = Editable.Factory.getInstance().newEditable(number.toString())
        }

        return itemView
    }

    private fun resetItem(index: Int) {
        binding.contentLayout.removeViewAt(index)
        binding.contentLayout.addView(buildItem(index, productList[index]), index)
    }

    private fun minusDrawable(white: Boolean): Drawable {
        val color = if (white) android.R.color.black else android.R.color.white
        val drawable = ContextCompat.getDrawable(requireContext(), R.drawable.ic_minus_circle)
        drawable!!.setTint(ContextCompat.getColor(requireContext(), color))

        return drawable
    }

    private fun plusDrawable(white: Boolean): Drawable {
        val color = if (white) android.R.color.black else android.R.color.white
        val drawable = ContextCompat.getDrawable(requireContext(), R.drawable.ic_plus_circle)
        drawable!!.setTint(ContextCompat.getColor(requireContext(), color))

        return drawable
    }
}



















